<template>
	<a-spin :spinning="loading">
		<a-card>
			<section slot="title">
				渠道对账
			</section>
			<a-row :gutter="10" type="flex">
				<a-col :span="4" style="margin-bottom: 20px;margin-right: 20px;">
					<section class="flex items-center">
						<span class="label">对账状态：</span>
						<a-select class="flex-1" @change="search" allow-clear placeholder="请选择对账状态" v-model="finished">
							<a-select-option v-for="item in reconciliationType" :key="item.value"
								:value="item.value">{{ item.name }}</a-select-option>
						</a-select>
					</section>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="4">
					<section class="flex items-center">
						<span class="label">预定渠道：</span>
						<a-select class="flex-1" @change="search" allow-clear placeholder="请选择预定渠道" v-model="channelId">
							<a-select-option v-for="item in channelData" :key="item.id"
								:value="item.id">{{ item.name }}</a-select-option>
						</a-select>
					</section>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="6">
					<section class="flex items-center">
						<span style="width: 140px;" class="label">费用生成时间：</span>
						<a-range-picker @change="search" v-model="createTimeArr" class="w-full" placeholder="请选择时间" />
					</section>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="8">
					<a-button class="mx-8" type="primary" @click="search">查询</a-button>
					<a-button class="mx-8" type="primary" @click="exportTable">导出</a-button>
					<a-button class="mx-8" type="primary" @click="getBatch(false)">批量对账</a-button>
					<a-button @click="reset">重置</a-button>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="4">
					<section class="flex items-center">
						<span class="label">订单号：</span>
						<a-input class="flex-1" @change="search" @keyup.enter="search" allow-clear placeholder="请输入平台订单号"
							:max-length="100" v-model="orderId" />
					</section>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="4">
					<section class="flex items-center">
						<span class="label">渠道订单号：</span>
						<a-input class="flex-1" @change="search" @keyup.enter="search" allow-clear placeholder="请输入渠道订单号"
							:max-length="100" v-model="channelOrderNo" />
					</section>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="4">
					<section class="flex items-center">
						<span class="label">联系方式：</span>
						<a-input class="flex-1" @change="search" @keyup.enter="search" allow-clear placeholder="请输入联系方式"
							:max-length="100" v-model="phone" />
					</section>
				</a-col>
				<a-col style="margin-bottom: 20px;margin-right: 20px;" :span="5">
					<section class="flex items-center">
						<span class="label">承租人：</span>
						<a-input class="flex-1" @change="search" @keyup.enter="search" allow-clear placeholder="请输入承租人" :max-length="100"
							v-model="travellerName" />
					</section>
				</a-col>
			</a-row>
			<a-table rowKey="id"  :row-selection="rowSelection" class="mt-16" :columns="columns" :data-source="data" :scroll="scroll" :pagination="pagination">
				<template #orderStatus="val, data">
				 <div v-if="data.orderStatus==1"> 待确认</div>
				 <div v-if="data.orderStatus==2">待取车</div>
				 <div v-if="data.orderStatus==3">待还车</div>
				 <div v-if="data.orderStatus==4">已还车</div>
				  <div v-if="data.orderStatus==-1">已取消</div>
				</template>
				<template #amount="val, data">
				 <div  :style="data.amount<1?'color:#F5222D':''"> {{data.amount}}</div>
				
				</template>
				
				<template #finished="val, data">
				 <div :style="data.finished?'color:#52c41a':'color:#faad14'"> {{data.finished?'已对账':'待对账'}}</div>
				</template>
				<template #action="val, data">
				 <div  > 
				  <span :style="data.finished?'color:#F5222D':'color:#13C2C2'" @click="getBatch(data.finished,data)">{{data.finished?'修改':'对账'}}</span>
				  <a style="color:#13C2C2;margin-left: 10px;" @click="getDetails(data)">详情</a>
				 </div>
				
				
				</template>
				
			</a-table>
			
		</a-card>
		<!--批量对账=弹框 -->
	<a-modal :visible="isvisible" :confirm-loading="confirmLoading" @ok="handleOk"
		@cancel="handleCancel">
		<div slot="title">{{!typeFinished?'对账':'修改'}}</div>
		<p v-if="!typeFinished" class="mt-15" style="color: red;font-size: 16px;text-align: center;font-weight: bold;">{{ ModalText }}</p>
		<section v-if="typeFinished"  class="flex items-center mt-30 mb-30" >
			<span class="label">对账状态：</span>
			<a-select class="flex-1"  allow-clear placeholder="请选择对账状态" v-model="finishednew">
				<a-select-option v-for="item in reconciliationType" :key="item.value"
					:value="item.value">{{ item.name }}</a-select-option>
			</a-select>
		</section>
	</a-modal>
	<!-- <a-modal :visible="isvisible" :closable="false" :confirm-loading="confirmLoading" @ok="handleOk"
		@cancel="handleCancel">
		 <section class="flex items-center">
		 	<span class="label">对账状态：</span>
		 	<a-select class="flex-1" @change="getData" allow-clear placeholder="请选择对账状态" v-model="finished">
		 		<a-select-option v-for="item in reconciliationType" :key="item.value"
		 			:value="item.value">{{ item.name }}</a-select-option>
		 	</a-select>
		 </section>
	</a-modal> -->
	 <detailss ref="detailss" ></detailss>
	</a-spin>
</template>
<script>
	import detailss from './detailss'
import { tableMixins } from '@/utils/mixins'
	import {getExportReconcile,getEditReconcile,getReconcileList} from '@/api/order/channelReconciliation'
	import {directConnection } from '@/api/geography'
	export default {
		components: {detailss},
mixins: [tableMixins],
		data() {
			return {
				loading: false,
				typeFinished:false,
				finished:false,
				channelId:undefined,
				phone:undefined,
				channelOrderNo:undefined,
				travellerName:undefined,
				orderId:undefined,
				isvisible:false,
				ModalText:'',
				confirmLoading:false,
				reconciliationType: [ //对账状态
					{
						name: '待对账',
						value: false
					},
					{
						name: '已对账',
						value: true
					}
				],
				columns: [
					{
						title: '订单号',
						dataIndex: 'orderId',
						width: 130,
						scopedSlots: {
							customRender: 'orderId'
						},
						 align: 'center'
					},
					{
						title: '订单状态',
						width: 120,
						dataIndex: 'orderStatus',
						scopedSlots: {
							customRender: 'orderStatus'
						},
						 align: 'center'
					},
					{
						title: '预定渠道',
						dataIndex: 'channelName',
						width: 120,
						scopedSlots: {
							customRender: 'channelName'
						},
						 align: 'center'
					},
					{
						title: '渠道订单号',
						dataIndex: 'channelId',
						width: 120,
						scopedSlots: {
							customRender: 'channelId'
						},
						 align: 'center'
					},
					{
						title: '承租人',
						dataIndex: 'travellerName',
						width: 120,
						scopedSlots: {
							customRender: 'travellerName'
						},
						 align: 'center'
					},
					{
						title: '联系电话',
						dataIndex: 'phone',
						width: 160,
						scopedSlots: {
							customRender: 'phone'
						},
						 align: 'center'
					},	{
						title: '费用生成时间',
						dataIndex: 'createTime',
						width: 160,
						scopedSlots: {
							customRender: 'createTime'
						},
						 align: 'center'
					},	{
						title: '线上费用类型',
						dataIndex: 'feeDesc',
						width: 120,
						scopedSlots: {
							customRender: 'feeDesc'
						},
						 align: 'center'
					},	{
						title: '线上费用金额(元)',
						dataIndex: 'amount',
						width: 120,
						scopedSlots: {
							customRender: 'amount'
						},
						 align: 'center'
					},	{
						title: '对账状态',
						dataIndex: 'finished',
						width: 160,
						scopedSlots: {
							customRender: 'finished'
						},
						 align: 'center'
					},
					{
						title: '操作',
						fixed: 'right',
						dataIndex: 'action',
						width: 100,
						scopedSlots: {
							customRender: 'action'
						},
						align: 'center'
					}
				],
				// total:0,
				// // pageNum:1,
				// pageNum:1,
				// rowsNum:10,
				data:[],
				  selectedRowKeys: [],
				  selectedRows:[],
				  channelData:[],//渠道
				   createTimeArr: [undefined, undefined],
				   arguments:[],//参数
				   	exportPath: false,
					finished:false,
					finishednew:false,
					pageSizeOptions:['10', '20', '30', '40','100']
				  // finished:,
				  

			}
		},
		computed: {
			scroll() {
				return {
					x: this.data.length === 0 ? undefined : 1200
				}
			},
			 rowSelection() {
			      const { selectedRowKeys,selectedRows } = this;
			      return {
			        selectedRowKeys,
			        onChange: this.onSelectChange,
			        hideDefaultSelections: true,
			        onSelection: this.onSelection,
			      }
				   },
		},
		async mounted() {
			this.getData()
          this.directConnections()
		},
		methods: {
			getDetails(data){
				console.log(data,'xxxx')
				this.$refs.detailss.open(data)
			},
			getBatch(type,item){
				 this.arguments=[]
			     console.log(type)
			     if(this.selectedRows.length==0&&type==false){
					  this.$message.error("至少得选择一笔费用")
					 return 
					
				 }else if(this.selectedRows.length!==0&&type==false){
					 let arrey=this.selectedRows
					  arrey.forEach(res=>{
						  if(res.finished==true){
							  this.$message.error("选择中存在已完成对账订单，请删除后再重新操作")
							  return 
						  }
						  if(res.finished==false){
							   this.arguments.push(res.id)
							   this.typeFinished=false
							   this.ModalText = `已选${this.selectedRows.length}笔费用，请确定是否对账完成`;
							   this.isvisible = true
						  }
						 
					  })
					 	
					
				 }else if(item&&type==true){
					 let arr=[]
					
					 arr.push(item)
					
					  arr.forEach(res=>{
					 						  this.arguments.push(res.id)
					  })
					  this.typeFinished=true
					 	this.isvisible = true
						console.log(this.arguments,'x')
						return
				 }
				 
				
			},
			handleOk(e) {
				   
					this.confirmLoading = true;
					setTimeout(() => {
						this.isvisible = false;
						this.confirmLoading = false;
						this.reconciliation()
						
					}, 2000);
				},
				handleCancel(e) {//关闭弹框
								console.log('Clicked cancel button');
								this.isvisible = false;
							},
			async reconciliation(){//批量对账
			    let data={
					ids:this.arguments,
					finished:!this.typeFinished
				}
				console.log(data,'canshu')
			       // return
					let res = await getEditReconcile(data)
					if (res) {
						this.$message.success(`${this.typeFinished?'修改':'对账'}成功`)
						this.getData()
						}
				},
			onSelectChange(selectedRowKeys,selectedRows) {
			      console.log('selectedRowKeys changed: ', selectedRowKeys,selectedRows);
			      this.selectedRowKeys = selectedRowKeys;
				  this.selectedRows=selectedRows
			    },
				directConnections(){
					let obj={
						// isEnabled:true,
						// 	isOnline:true,
						pageNum:1,
						rowsNum:30
					}
					directConnection(obj).then((data) => {
					this.channelData = data.items
					})
				},
          getData() {
			  if(!this.orderId)this.orderId=undefined
			  if(!this.channelOrderNo)this.channelOrderNo=undefined
			  if(!this.phone)this.phone=undefined
			  if(!this.travellerName)this.travellerName=undefined
            this.loading = true
            getReconcileList(this.getParams()).then(data => {
              this.total = data.rowCount
              this.data = data.items
            }).catch(err => {
            }).finally(() => this.loading = false)
          },
		  exportTable() {
		  	if (this.exportPath) return false
		  	this.exportPath = true
		          getExportReconcile(this.getParams()).then(res => {
		              console.log(`res`,res)
		              this.dataURLtoDownload(res.base64, res.name)
		  		// if (res.domain) {
		  		// 	this.$refs.download.href = res.domain + res.filePath
		  		// 	setTimeout(() => this.$refs.download.click())
		  		// } else {
		  		// 	this.$message.warning('暂无符合条件的数据！')
		  		// }
		  	}).finally(() => {
		  		this.exportPath = false
		  	})
		  },
		  dataURLtoDownload(dataurl, name) {
		      var bstr = atob(dataurl), //解析 base-64 编码的字符串
		          n = bstr.length,
		          u8arr = new Uint8Array(n) //创建初始化为0的，包含length个元素的无符号整型数组
		      while (n--) {
		          u8arr[n] = bstr.charCodeAt(n) //返回字符串第一个字符的 Unicode 编码
		      }
		      let blob = new Blob([u8arr], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) //转化成blob
		      let url = URL.createObjectURL(blob) //这个新的URL 对象表示指定的 File 对象或 Blob 对象
		      let a = document.createElement('a') //创建一个a标签
		      a.href = url
		      a.download = name
		      a.click()
		      URL.revokeObjectURL(a.href) //释放之前创建的url对象
		  },
		  getParams() {
		    return {
			// "sort": {
			//   "additionalProp1": 0,
			//   "additionalProp2": 0,
			//   "additionalProp3": 0
			// },
			finished: this.finished,
			 channelId: this.channelId,
			 createTimeStart: this.$utils.getStartTime(this.createTimeArr[0]),
			 createTimeEnd: this.$utils.getEndTime(this.createTimeArr[1]),
			 orderId: this.orderId,
			 channelOrderNo: this.channelOrderNo,
			 phone: this.phone,
			  travellerName: this.travellerName,
		      pageNo: this.pageNum,
		      pageSize: this.rowsNum,
		     
		    }
		  },
          search() {
            this.pageNum = 1
            this.getData()
          },
		  reset() {
			   this.createTimeArr=[undefined, undefined],
			   this.finished=undefined
			   this.channelId=undefined
			   this.orderId=undefined
			   this.channelOrderNo=undefined
			   this.phone=undefined
			   this.travellerName=undefined
		    // this.orderId = ''
		    // this.travellerName = ''
		    // this.channelId = undefined
		    // this.status = undefined
		    // this.vehicleTypeId = undefined
		    // this.phone = ''
		    // this.reservingPickupTimeArr = [undefined, undefined]
		    // this.realityPickupTimeArr = [undefined, undefined]
		    // this.reservingReturnTimeArr = [undefined, undefined]
		    // this.realityReturnTimeArr = [undefined, undefined]
		    this.search()
		  },
		}
	}
</script>
<style scoped>

</style>